/**
 * 随机打乱数组并返回打乱后的数组和交换步骤
 * @param {Array} arr - 要打乱的原始数组
 * @returns {{shuffled: Array, swaps: Array}} - 包含打乱后的数组和交换步骤的对象
 */
export function shuffle(arr) {
    const shuffled = [...arr];
    const swaps = [];
    const length = shuffled.length;

    for (let i = length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        // 记录交换步骤
        swaps.push([i, j]);
        // 交换元素
        [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }

    return { shuffled, swaps };
}

/**
 * 根据交换步骤恢复数组
 * @param {Array} shuffled - 打乱后的数组
 * @param {Array} swaps - 记录的交换步骤
 * @returns {Array} - 恢复后的数组
 */
export function restoreShuffle(shuffled, swaps) {
    const restored = [...shuffled];
    // 反向执行交换步骤
    for (let i = swaps.length - 1; i >= 0; i--) {
        const [index1, index2] = swaps[i];
        [restored[index1], restored[index2]] = [restored[index2], restored[index1]];
    }
    return restored;
}
